<template>
  <el-container>
    <el-aside width="200px">
      <el-scrollbar wrap-style="height:calc(100vh - 175px);">
        <el-tree
          ref="treeEl"
          style="max-width: 600px"
          node-key="id"
          :props="orgTreeProps"
          :load="loadNode"
          :default-expanded-keys="expandedKeys"
          :expand-on-click-node="false"
          lazy
          @node-click="clickTreeNode"
        >
          <template #default="{ node }">
            <template v-if="node.data.typeIcon">
              <Icon
                :icon="node.data.typeIcon"
                :color="node.data.typeColor"
                :hoverColor="node.data.typeColor"
              />
            </template>
            <template v-else>
              <Icon icon="octicon:organization" color="#008000" hoverColor="#008000" />
            </template>
            <span class="ml-1">{{ node.label }}</span>
          </template>
        </el-tree>
      </el-scrollbar>
    </el-aside>
    <WsmTable
      ref="table"
      v-model="queryFormType"
      load-url="/rbac-server/rbac/org/page"
      :change-load="true"
    >
      <template #title>{{ title }}</template>
      <template #query="{ data }">
        <el-form-item :label="t('rbac.org.orgName')">
          <el-input v-model="data.orgName.value" />
        </el-form-item>
      </template>
      <template #button="{ row }">
        <el-button type="primary" v-hasPermi="'add'" @click="addForm.show()">{{
          t('common.add')
        }}</el-button>
        <el-button type="warning" v-hasPermi="'reall'" @click="reall()">{{
          t('rbac.org.reall')
        }}</el-button>
        <template v-if="row">
          <template v-if="row.id != 'TOP'">
            <el-button v-hasPermi="'update'" @click="update(row.id)" type="primary">{{
              t('common.update')
            }}</el-button>
            <el-button v-hasPermi="'delete'" @click="del(row.id)" type="danger">{{
              t('common.delete')
            }}</el-button>
          </template>
          <el-button v-hasPermi="'bind'" @click="bind(row.id)" type="warning">{{
            t('common.bind')
          }}</el-button>
        </template>
      </template>
      <template #column>
        <el-table-column type="expand">
          <template #default="props">
            <div m="4">
              <p class="b-2 m-l-10">{{ t('rbac.org.orgLocation') }}: {{ props.row.orgLocation }}</p>
              <p class="b-2 m-l-10"
                >{{ t('rbac.org.orgShortName') }}: {{ props.row.orgShortName }}</p
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="orgLevel" :label="t('rbac.org.orgLevel')" width="120">
          <template #default="scope">
            {{ scope.row.orgLevel + t('rbac.org.orgLevelSuffix') }}
          </template>
        </el-table-column>
        <el-table-column prop="typeName" :label="t('rbac.org.orgType')" width="120" />
        <el-table-column prop="id" :label="t('rbac.org.id')" width="120" />
        <el-table-column prop="orgName" :label="t('rbac.org.orgName')" width="180" />
        <el-table-column prop="areaName" :label="t('rbac.org.areaName')" />
      </template>
    </WsmTable>
  </el-container>

  <WsmForm
    ref="addForm"
    v-model="addData"
    submit-url="/rbac-server/rbac/org/add"
    :width="600"
    :init-data="initData"
    label-width="100px"
    :title="t('rbac.org.addTitle')"
    @success="flushed"
  >
    <template #default="{ form }">
      <el-row>
        <el-col :span="12">
          <el-form-item prop="id" :label="t('rbac.org.id')">
            <el-input v-model="form.id" :placeholder="t('rbac.org.id')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="orgName" :label="t('rbac.org.orgName')">
            <el-input v-model="form.orgName" :placeholder="t('rbac.org.orgName')" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="orgLevel" :label="t('rbac.org.orgLevel')">
            <el-input
              type="number"
              v-model="form.orgLevel"
              :min="1"
              :max="10"
              :placeholder="t('rbac.org.orgLevel')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="orgType" :label="t('rbac.org.orgType')">
            <el-select v-model="form.orgType" :placeholder="t('rbac.org.orgType')">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.typeName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item prop="note" :label="t('rbac.org.note')">
            <el-input type="textarea" v-model="form.note" :placeholder="t('rbac.org.note')" />
          </el-form-item>
        </el-col>
      </el-row>
    </template>
  </WsmForm>

  <WsmForm
    ref="updateForm"
    v-model="updateData"
    load-url="/rbac-server/rbac/org/get"
    submit-url="/rbac-server/rbac/org/update"
    :width="600"
    label-width="100px"
    :title="t('rbac.org.updateTitle')"
    @success="flushed"
  >
    <template #default="{ form }">
      <el-row>
        <el-col :span="24">
          <el-form-item prop="orgName" :label="t('rbac.org.orgName')">
            <el-input v-model="form.orgName" :placeholder="t('rbac.org.orgName')" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="orgLevel" :label="t('rbac.org.orgLevel')">
            <el-input
              type="number"
              v-model="form.orgLevel"
              :min="1"
              :max="10"
              :placeholder="t('rbac.org.orgLevel')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="orgType" :label="t('rbac.org.orgType')">
            <el-select v-model="form.orgType" :placeholder="t('rbac.org.orgType')">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.typeName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item prop="orgShortName" :label="t('rbac.org.orgShortName')">
            <el-input v-model="form.orgShortName" :placeholder="t('rbac.org.orgShortName')" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item prop="note" :label="t('rbac.org.note')">
            <el-input type="textarea" v-model="form.note" :placeholder="t('rbac.org.note')" />
          </el-form-item>
        </el-col>
      </el-row>
    </template>
  </WsmForm>

  <WsmForm
    ref="bindForm"
    v-model="bindData"
    load-url="/rbac-server/rbac/resource/getResourceOrg"
    label-position="top"
    submit-url="/rbac-server/rbac/resource/updateResourceOrg"
    :title="t('rbac.bindTitle')"
  >
    <template #default="{ form }">
      <el-form-item prop="resId" :label="t('rbac.bindResource')">
        <el-checkbox-group v-model="form.resId">
          <el-checkbox
            v-for="item in resources"
            :key="item.id"
            :label="item.resName"
            :value="item.id"
          >
            {{ item.resName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </template>
  </WsmForm>
</template>
<script setup lang="ts">
import { WsmTable } from '@/components/WsmTable'
import { WsmForm } from '@/components/WsmForm'
import { QueryFormType, QueryType } from '@/components/WsmTable/src/types'
import { computed, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, ElTree } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { FormDataType } from '@/components/WsmForm/src/types'
import { getTreeChildApi, delApi, reallApi } from '@/api/rbac/org'
import { listAllApi } from '@/api/rbac/orgtype'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { OrgTypeType } from '@/api/rbac/orgtype/types'
import { useUserStore } from '@/store/modules/user'
import { OrgTreeDataType } from './types'
import { OrgType } from '@/api/login/types'
import { ResourceType } from '@/api/rbac/resource/types'
import { listResourceApi } from '@/api/rbac/resource'

const options = ref<OrgTypeType[]>([])

const { t } = useI18n()

const userStore = useUserStore()
//列表标题
const orgName = ref(t('rbac.org.orgRoot'))

//表格对象
const table = ref()

//树配置项
const orgTreeProps = {
  parentId: 'parentId',
  label: 'orgName',
  isLeaf: 'isLeaf'
}
var treeData: OrgTreeDataType[] = [
  {
    id: 'root',
    parentId: '',
    orgName: t('rbac.org.orgRoot'),
    isLeaf: false
  }
]

const expandedKeys = ref(['root'])

const treeEl = ref<InstanceType<typeof ElTree>>()

const parentNode = ref<OrgTreeDataType>()

//更新树
const updateKeyChildren = async () => {
  let parentId = 'root'
  if (parentNode.value) {
    if (parentNode.value.isLeaf) {
      parentId = parentNode.value.parentId
    } else {
      parentId = parentNode.value.id
    }
  }
  const rs = await getTreeChildApi({
    parentId: parentId
  })
  if (rs.success) {
    treeEl.value?.updateKeyChildren(parentId, rs.data)
  }
}

//树的点击事件
const clickTreeNode = (data: OrgTreeDataType) => {
  initParams(data)
  parentNode.value = data
  table.value.load(1)
}

const initParams = (data: OrgType) => {
  queryFormType.parentId.value = data.id
  orgName.value = data.orgName
  initData.value.parentId = data.id
}

const title = computed(() => {
  return orgName.value + '(' + queryFormType.parentId.value + ')'
})

//加载树代码
const loadNode = async (node: Node, resolve: (data: OrgTreeDataType[]) => void) => {
  if (node.level == 0) {
    const userTypeId = userStore.getUserInfo?.userType.id
    if (userTypeId == 'administrator') {
      initParams(treeData[0])
      return resolve(treeData)
    } else {
      const queryOrg = userStore.getUserInfo?.queryOrg as OrgTreeDataType
      expandedKeys.value = [queryOrg.id]
      initParams(queryOrg)
      queryOrg.isLeaf = false
      queryOrg.isParent = true
      return resolve([queryOrg])
    }
  }
  const rs = await getTreeChildApi({ parentId: node.data.id })
  if (rs.success) {
    return resolve(rs.data)
  }
}

//新增表单对象
const addForm = ref()
const initData = ref({
  parentId: 'root'
})
const addData: FormDataType = reactive({
  id: '',
  parentId: 'root',
  orgName: '',
  orgType: '',
  orgLevel: '',
  note: ''
})

//修改表单对象
const updateForm = ref()
const updateData: FormDataType = {
  id: '',
  parentId: '',
  orgName: '',
  orgType: '',
  orgLevel: '',
  orgShortName: '',
  note: ''
}

const queryFormType: QueryFormType = {
  parentId: {
    value: 'root',
    clear: false
  },
  orgName: {
    value: '',
    queryType: QueryType.LIKE
  }
}

const loadOrgType = async () => {
  const rs = await listAllApi({})
  if (rs.success) {
    options.value = rs.data
  }
}
//加载组织类型
loadOrgType()

const update = (id: string) => {
  updateForm.value.show({ id })
}
const del = async (id: string) => {
  ElMessageBox.confirm(t('common.delMessage'), t('common.delWarning'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  }).then(async () => {
    const rs = await delApi(id)
    if (rs.success) {
      updateKeyChildren()
      table.value.load(1)
    }
  })
}
const reall = async () => {
  ElMessageBox.confirm(t('rbac.org.reallMsg'), t('common.delWarning'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  }).then(async () => {
    const rs = await reallApi()
    if (rs.success) {
      ElMessage.success(rs.message)
      table.value.load(1)
    }
  })
}

//绑定表单对象
const bindForm = ref()
const bindData: FormDataType = {
  orgId: '',
  resId: []
}
const bind = (orgId: string) => {
  bindForm.value.show({ orgId })
}

const resources = ref<ResourceType[]>([])

//加载可以配置的资源
const loadResource = async () => {
  const rs = await listResourceApi()
  if (rs.success) {
    resources.value = rs.data
  }
}
loadResource()

const flushed = () => {
  updateKeyChildren()
  table.value.load(1)
}
</script>

<style scoped></style>
